package com.atguigu.fruit.controllers;

import com.atguigu.fruit.pojo.Fruit;
import com.atguigu.fruit.service.FruitService;
import com.atguigu.myssm.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
public class FruitControllers{
    private FruitService fruitService = null;
    private String index(String open, String keyword, Integer pageNo, HttpServletRequest req) {
        HttpSession session = req.getSession();
        if(pageNo == null) {
            pageNo = 1;
        }
        if(StringUtil.isNotEmpty(open) && "search".equals(open)) {
            pageNo = 1;
            if(StringUtil.isEmpty(keyword)){
                keyword = "";
            }
            session.setAttribute("keyword",keyword);
        } else {
            Object keywordObj = session.getAttribute("keyword");
            if(keywordObj != null) {
                keyword = (String) keywordObj;
            } else {
                keyword = "";
            }
        }
        session.setAttribute("pageNo",pageNo);
        List<Fruit> fruitList = fruitService.getFruitList(keyword, pageNo);
        session.setAttribute("fruitList",fruitList);
        int fruitCount = fruitService.getPageCount(keyword);
        session.setAttribute("pageCount",fruitCount);
        return "index";
    }
    private String add(String fname, Integer price, Integer fcount, String remark) {
        Fruit fruit = new Fruit(0,fname , price , fcount , remark) ;
        fruitService.addFruit(fruit);
        return "redirect:fruit.do";
    }
    private String delete(Integer fid) {
        if(fid != null) {
            fruitService.delFruit(fid);
            return "redirect:fruit.do";
        }
        return null;
    }
    private String edit(Integer fid, HttpServletRequest req) {
        if(fid != null){
            Fruit fruit = fruitService.getFruitByFid(fid);
            req.setAttribute("fruit",fruit);
            return "edit";
        }
        return null;
    }
    private String update(Integer fid, String fname, Integer price, Integer fcount, String remark) {
        fruitService.updateFruit(new Fruit(fid,fname, price ,fcount ,remark ));
        return "redirect:fruit.do";
    }
}
